import { defineConfig, loadEnv } from "vite";
import UnoCSS from "unocss/vite";
import vue from "@vitejs/plugin-vue";
import path, { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";
import vueJsx from "@vitejs/plugin-vue-jsx";
import postCssPxToRem from "postcss-pxtorem";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import { ViteImageOptimizer } from "vite-plugin-image-optimizer";
import { createHtmlPlugin } from "vite-plugin-html";
import svgLoader from "vite-svg-loader";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { iphone6Ratio, designRatio, precision } from "./src/config/app.ts";
import { enableCDN } from "./src/config/cdn.ts";
// @ts-ignore
import { svgBuilder } from "./src/plugins/svgBuilder.js";
// @ts-ignore
import basicSsl from "@vitejs/plugin-basic-ssl";
export default defineConfig(({ mode }) => {
  const ENV_DIR = "./env";
  const { VITE_ENV, VITE_PROXY_PATH, VITE_PROXY_TARGET } = loadEnv(
    mode,
    resolve(process.cwd(), ENV_DIR)
  );
  return {
    define: {
      __APP_ENV__: JSON.stringify(process.env.VITE_ENV || "development")
    },
    base: "/",
    envDir: ENV_DIR,
    envPrefix: ["VITE_"],
    plugins: [
      basicSsl(),
      UnoCSS(),
      svgLoader(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), "src/assets/svg")],
        symbolId: "icon-[dir]-[name]"
      }),
      svgBuilder("./src/assets/svg/"),
      enableCDN(VITE_ENV != "production"),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            title: "Home"
          }
        }
      }),
      vue(),
      vueJsx(),
      AutoImport({
        imports: ["vue", "vue-router", "pinia", "vue-i18n"],
        resolvers: [VantResolver()],
        dirs: ["./src/hooks/*", "./src/assets/js/*"],
        dts: "src/typings/auto-import.d.ts",
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/]
      }),
      Components({
        resolvers: [VantResolver()],
        dirs: ["src/components/common"],
        dts: "src/typings/components.d.ts",
        extensions: ["vue"],
        globalNamespaces: []
      }),
      VueSetupExtend(),
      ViteImageOptimizer({
        png: {
          quality: 100
        },
        jpg: {
          quality: 100
        },
        jpeg: {
          quality: 100
        },
        webp: {
          quality: 100
        }
      })
    ],
    build: {
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: false,
      minify: "terser",
      chunkSizeWarningLimit: 1024 * 10,
      terserOptions: {
        output: {
          comments: false,
          beautify: false
        },
        compress: {
          drop_console: false,
          drop_debugger: true
        }
      },
      rollupOptions: {
        input: {
          index: resolve(__dirname, "index.html")
        },
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks: id => {
            if (id.includes("node_modules")) {
              return "vendor";
            }
            return undefined;
          }
        }
      }
    },
    server: {
      open: true,
      port: 65515,
      host: "0.0.0.0",
      // https: true,
      proxy: {
        /*"/api": {
          target: VITE_PROXY_TARGET,
          changeOrigin: true,
          secure: false,
          rewrite: path => path.replace(/^\/api/, "")
        },*/
        [VITE_PROXY_PATH]: {
          target: VITE_PROXY_TARGET,
          changeOrigin: true,
          secure: false,
          rewrite: path => path.replace(new RegExp(`^${VITE_PROXY_PATH}`), "")
        }
      }
    },
    resolve: {
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
      alias: {
        "@": path.resolve(__dirname, "src"),
        comps: path.resolve(__dirname, "src/components")
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use '@/styles/variables.scss' as *;`
        }
      },
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue({ file }: any) {
              return file.indexOf("vant") !== -1 ? iphone6Ratio : designRatio;
            },
            propList: ["*"],
            unitPrecision: precision,
            // selectorBlackList: ["van"], // 不被转换rem的样式
            exclude: (filePath: string) => {
              if (/src\/styles\/initial.scss/.test(filePath)) {
                return true;
              }
              return false;
            }
          })
        ]
      }
    }
  };
});
